package com.cszb.springcloudhystrixserver.service;

import com.cszb.springcloudhystrixserver.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @author:CrazyShaQiuShi
 * @email: 1047812462@qq.com
 * @createTime: 2018-10-11 16:38
 * @version: 1.0
 */
@Service
public class HystrixService {
    @Autowired
    private RestTemplate restTemplate;

    public static final Logger LOGGER = LoggerFactory.getLogger(HystrixService.class);

    @HystrixCommand(fallbackMethod = "fallback")
    public User findById(Long id) {
        // http://服务提供者的serviceId/url
        System.out.println(id);
        return this.restTemplate.getForObject("http://cszb-sc-ribbon-server/ribbon/" + id, User.class);
    }

    /**
     * hystrix fallback⽅法
     *
     * @param id
     * @return
     */
    public User fallback(Long id) {
        LOGGER.info("异常发⽣，进⼊fallback⽅法,接收的参数：id = {}", id);
        User user = new User();
        user.setId(-1L);
        user.setUsername("default username");
        user.setAge(0);
        return user;
    }
}
